package com.fortune.cat.resolver;

import com.fortune.cat.bean.RequestRateLimiterConfig;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import static com.fortune.cat.enums.RateLimiterKeyResolverEnums.PATH_HEADER;
import static com.fortune.cat.resolver.PathKeyResolver.antPathMatcher;

/**
 * @author zhaozeyang
 * @date 2019/4/26 14:16
 * @description
 */
@Component
public class PathHeaderKeyResolver extends AbstractKeyResolver {
    @Override
    public Integer getType() {
        return PATH_HEADER.getType();
    }

    @Override
    protected String doResolve(ServerWebExchange exchange) {
        RequestRateLimiterConfig.Header header = requestRateLimiterConfig.getHeader();
        String path = exchange.getRequest().getPath().value();
        String method = exchange.getRequest().getMethod().name();
        if (method.equalsIgnoreCase(requestRateLimiterConfig.getMethod()) & antPathMatcher.match(requestRateLimiterConfig.getPath(), path)) {
            if (header.getValue().equals(exchange.getRequest().getHeaders().getFirst(header.getHeader()))) {
                return method.concat("-").concat(requestRateLimiterConfig.getPath()).concat("-").concat(header.getHeader()).concat("-").concat(header.getValue());
            }
        }
        return null;
    }
}
